from django.shortcuts import render
from goods.models import GoodsCategory
from django.core.paginator import Paginator ,EmptyPage#分页器
# Create your views here.
from datetime import datetime
from django.utils import  timezone
from django.views import View
from django import http
from contents.utils import get_categories
from goods.utils import get_breadcrumb
from goods.models import SKU,GoodsVisitCount1


class DetailVisitView(View):
    """统计分类商品的访问量"""

    def post(self, request, category_id):
        # 接收参数和校验参数
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.HttpResponseForbidden('category_id 不存在')

        # 获取当天的日期
        t = timezone.localtime()
        # 获取当天的时间字符串
        today_str = '%d-%02d-%02d' % (t.year, t.month, t.day)
        # 将当天的时间字符串转成时间对象datetime，为了跟date字段的类型匹配 2019:05:23  2019-05-23
        today_date = datetime.strptime(today_str, '%Y-%m-%d') # 时间字符串转时间对象；datetime.strftime() # 时间对象转时间字符串

        # 判断当天中指定的分类商品对应的记录是否存在
        try:
            # 如果存在，直接获取到记录对应的对象
            counts_data = GoodsVisitCount1.objects.get(date=today_date, category=category)
        except GoodsVisitCount1.DoesNotExist:
            # 如果不存在，直接创建记录对应的对象
            counts_data = GoodsVisitCount1()

        try:
            counts_data.category = category
            counts_data.count += 1
            counts_data.date = today_date
            counts_data.save()
        except Exception as e:
            return http.HttpResponseServerError('统计失败')

        # 响应结果
        return http.JsonResponse({'code': '200', 'errmsg': 'OK'})




class DetailView(View):
    """商品详情页"""

    def get(self, request, sku_id):
        """提供商品详情页"""
        # 接收和校验参数
        try:
            # 查询sku
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            # return http.HttpResponseNotFound('sku_id 不存在')
            return render(request, '404.html')

        # 查询商品分类
        categories = get_categories()

        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category)

        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options
        print(sku.category_id)
        # 构造上下文
        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': goods_specs,
        }

        return render(request, 'detail.html', context)










class HotGoodView(View):
    ''''热销排行'''
    def get(self,request,detile_id):
        #查询指定分类的SKU信息，必须上架，按照销量有高到底排序，切片去两个数据
        skus = SKU.objects.filter(category=detile_id,is_launched=True).order_by('-sales')[:2]
        #将模型列表转成字典列表，构造json数据
        hot_skus=[]
        for sku in skus:
            sku_dict = {
                'id':sku.id,
                'name':sku.name,
                'price':sku.price,
                'default_image_url':sku.default_image.url
            }
        hot_skus.append(sku_dict)
        return http.JsonResponse({'code':'200','errmsg':'ok','hot_skus':hot_skus})

class ListView(View):
    '''商品列表页'''

    def get(self,request,detile_id,page_num):

        # 获取sort
        sort = request.GET.get('sort','default')
        if sort=='price':
            sort_file = 'price'
        elif sort =='hot':
            sort_file = '-sales'
        else:
            sort ='default'
            sort_file = 'create_time'
        #校验参数
        try:
            category =GoodsCategory.objects.get(id = detile_id)
        except GoodsCategory.DoesNotExist:
            return http.HttpResponseForbidden('参数错误')

        #获取分类数据
        categories = get_categories()
        cat2 = category.parent
        #查询面包屑导航
        breakcrumb = get_breadcrumb(category)
        #分页及排序查询
        try:
            skus = category.sku_set.filter(is_launched = True).order_by(sort_file)
        except EmptyPage:
            return http.HttpResponseForbidden('发生错误')
        #获取看的那一页
        paginator = Paginator(skus,5)
        #获取下一页
        page_skus = paginator.page(page_num)
        #获取总页数
        totle_page = paginator.num_pages
        #构造上下文章
        context = {
            "categories":categories,
            'breadcrumb':breakcrumb,
            'page_skus':page_skus,
            'total_page':totle_page,
            'page_num':page_num,
            'sort':sort,
            'category_id':detile_id,
        }
        print(context)
        return render(request,'list.html',context)





